package com.ykt.controller;

import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;
import com.ykt.common.utils.DateUtil;
import com.ykt.common.utils.FileUtil;
import com.ykt.common.utils.UB;
import com.ykt.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

/**
 * 用户日志接口，做业务，性能统计分析
 *
 * @author long.hua
 * @version 1.0.0
 * @since 2016-05-29 13:06
 */
public class UserLoggerController extends BaseController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    private static String homeDir = PropKit.get("upload.user.log");
    private static String businessDir = "business/";
    private static String performanceDir = "performance/";


    // 业务统计日志
    public void business() {
        save2Disk(businessDir);
        returnJson(ResultVo.success());
    }

    // 性能统计日志
    public void performance() {
        save2Disk(performanceDir);
        returnJson(ResultVo.success());
    }

    private void save2Disk(String logDir) {
        UploadFile uploadFile = super.getFile();
        if (uploadFile == null) {
            returnJson(ResultVo.failure(null, "上传文件为空！"));
            return;
        }

        String originalFile = uploadFile.getOriginalFileName();
        int userId = UB.i(getPara("userId"));
        String datetime = DateUtil.ymdhms1(new Date());
        String fileName = userId + "-" + datetime + ".log";
        String fullPath = homeDir + logDir + fileName;

        FileInputStream in = null;
        try {
            in = new FileInputStream(uploadFile.getFile());
            FileUtil.write(in, fullPath);
            LOGGER.info("保存上传的文件: {} 成功，文件存储全路径：{}", originalFile, fullPath);
        } catch (Exception e) {
            LOGGER.error("保存上传的文件: {} 异常，文件存储全路径：{}", originalFile, fullPath);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error("保存上传的文件: {} 异常，文件存储全路径：{}", originalFile, fullPath);
                }
            }
        }
    }

}
